
import json
from datetime import datetime
from flask import Blueprint, render_template, request, current_app
import requests
from flask_login import login_required, current_user
from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Role

admin_prisoners = Blueprint('adminPrisoners', __name__, url_prefix='/admin/prisoners')


# 获取体征设备管理页面
@admin_prisoners.get('/')
@login_required
def main():
    user_info=current_user
    access_time=datetime.now().strftime("%Y年%m月%d日 %H时%M分%S秒")
    return render_template('admin/prisoners/main.html', real_name=user_info.realname, access_time=access_time)


# 体征设备分页查询
@admin_prisoners.get('/data')
def data():
    page = request.args['page']
    page_size = request.args['limit']
    if 'content' not in request.args:
        content = ''
    else:
        content = request.args['content']
    response = requests.post(url=current_app.config['EMERGENCY_URL'] + '/prisoners',
                             headers={
                                 'Content-type': 'application/json'
                             },
                             data=json.dumps({
                                 "page": int(page) - 1,
                                 "page_size": page_size,
                                 "total_count": True,
                                 "search": content
                             }))
    data = json.loads(response.text)
    data['code'] = 0
    data['count'] = response.headers['Total-Count']
    data['limit'] = page_size
    return data


# 情景增加
@admin_prisoners.get('/add')
def add():
    roles = Role.query.all()
    return render_template('admin/prisoners/add.html', roles=roles)



@admin_prisoners.post('/save')
def save():

    req_json = request.json
    a = req_json.get("roleIds")
    code = xss_escape(req_json.get('code'))
    name = xss_escape(req_json.get('name'))
    sex = xss_escape(req_json.get('sex'))
    birthday = xss_escape(req_json.get('birthday'))
    id_number = xss_escape(req_json.get('id_number'))
    native_place = xss_escape(req_json.get('native_place'))
    address = xss_escape(req_json.get('address'))
    charges = xss_escape(req_json.get('charges'))
    yg_type = xss_escape(req_json.get('yg_type'))
    dept_id = xss_escape(req_json.get('deptId'))
    try:
        dept_id=int(dept_id)
    except:
        dept_id=None
    room_num = xss_escape(req_json.get('room_num'))
    bed_num = xss_escape(req_json.get('bed_num'))
    if sex==0 or sex=="0":
        sex="男"
    elif sex==1 or sex=="1":
        sex="女"
    else:
        sex="武装直升机"
    response = add_api(code,name, sex, birthday, id_number, native_place, address, charges, yg_type, dept_id, room_num,
                       bed_num)
    if response['code']==200:
        return success_api(msg="增加成功")
    else :
        return fail_api(msg=response['message'])


def add_api(code,name, sex, birthday, id_number, native_place, address, charges, yg_type, dept_id, room_num, bed_num):
    body = {
        "code": code,
        "sex": sex,
        "name": name,
        "birthday": birthday,
        "id_number": id_number,
        "native_place": native_place,
        "address": address,
        "charges": charges,
        "yg_type": yg_type,
        "dept_id": dept_id,
        "room_num": room_num,
        "bed_num": bed_num,
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/prisoners/create', json=body).json()
    return req

# 删除情景
@admin_prisoners.delete('/remove/<int:id>')
@authorize("admin:prisoners:remove", log=True)
def delete(id):
    body = {
        "ids": [id]
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/prisoners/delete', json=body).json()
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])


#  编辑情景
@admin_prisoners.get('/edit')
@authorize("admin:prisoners:edit", log=True)
def edit():
    prisoner=request.args.to_dict()
    if 'native_place' not in prisoner:
        native = []
    else:
        native = prisoner['native_place'].split('-')
    if len(native)<3:
        prisoner['native_province']=''
        prisoner['native_city'] = ''
        prisoner['native_county'] = ''
    else:
        prisoner['native_province'] = native[0]
        prisoner['native_city'] = native[1]
        prisoner['native_county'] = native[2]

    if 'address' not in prisoner:
        address=[]
    else:
        address = prisoner['address'].split('-')
    if len(address)<4:
        prisoner['address_province']=''
        prisoner['address_city'] = ''
        prisoner['address_county'] = ''
        prisoner['address_detail'] = ''
    else:
        prisoner['address_province'] = address[0]
        prisoner['address_city'] = address[1]
        prisoner['address_county'] = address[2]
        prisoner['address_detail'] = address[3]

    if 'sex' not in prisoner:
        prisoner['gender'] = ''
    elif prisoner['sex'] == '男' or prisoner['sex'] == '男性':
        prisoner['gender'] = '0'
    elif prisoner['sex'] == '女' or prisoner['sex'] == '女性':
        prisoner['gender'] = '1'
    else:
        prisoner['gender'] = ''

    roles = Role.query.all()
    checked_roles = []
    for r in roles:
        checked_roles.append(r.id)

    return render_template('admin/prisoners/edit.html', prisoner=prisoner, roles=roles, checked_roles=checked_roles)


#  编辑情景
@admin_prisoners.put('/update')
def update():
    req_json = request.json
    sex = req_json['sex']
    if sex==0 or sex=="0":
        sex="男"
    elif sex==1 or sex=="1":
        sex="女"
    else:
        sex="武装直升机"
    req_json['sex']=sex
    print("req_json",req_json)
    req_json['dept_id']=int(req_json['dept_id'])
    req = requests.post(url=current_app.config['EMERGENCY_URL']+'/prisoners/update', json=req_json).json()
    if req['code'] == 200:
        return success_api(msg="更新成功")
    else:
        return fail_api(msg=req['message'])


# 批量删除
@admin_prisoners.delete('/batchRemove')
@authorize("admin:prisoners:remove", log=True)
def batch_remove():
    ids = list(map(int, request.form.getlist('ids[]')))
    body = {
        "ids": ids
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/prisoners/delete', json=body).json()
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])